######################################################################
# Replaces NAs with row averages. If the entire row is NA, with 0's
######################################################################
ep.nanimprowavg <- function ( M ) {
  means = apply ( M, 1, mean, na.rm=T );
  means[is.na(means)]=0;
  means = repmat ( means, 1, ncol(M) );
  mask = is.na(M);
  M[mask] = means[mask];
  return(M);
}

repmat <- function (a,n,m) {
  kronecker(matrix(1,n,m),a)
}

ae.knnimpute<- function (data, k = 10) 
{  # Edited from pamr.knnimpute
    require(pamr)
    x <- data
    p <- ncol(x)	# P is the ncol of x
    N <- nrow(x)	# N is the nrow of x
    
    if ( length ( which ( apply ( is.na (data), 2, sum ) == nrow(data) ) ) > 0 ) stop ( "ERROR: A column has all missing values!")
    if ( sum ( is.na ( x ) ) / prod ( dim ( x ) ) > 0.15 ) stop ( "Greater than 15% missing values in data" )
    
    nas <- is.na(drop(x %*% rep(1, p)))
    xcomplete <- x[!nas, ]
    xbad <- x[nas, , drop = FALSE]
    xnas <- is.na(xbad)
    xbadhat <- xbad
    cat(nrow(xbad), fill = TRUE)
    for (i in seq(nrow(xbad))) {
        cat(i, fill = TRUE)
        xinas <- xnas[i, ]
        xbadhat[i, ] <- nnmiss(xcomplete, xbad[i, ], xinas, K = k)
    }
    x[nas, ] <- xbadhat
    data2 <- x
    detach("package:pamr")
    # temporary fix to make sure imputation results in no missing vals!
    if ( sum(is.na(data2)) != 0 ) { data2[is.na(data2)] <- 0 }
    return(data2)
}

ep.knnimpute <- function (data, k = 10) {
  x <- data
  p <- ncol(x)	# P is the ncol of x
  N <- nrow(x)	# N is the nrow of x

  if ( length ( which ( apply ( is.na (data), 2, sum ) == nrow(data) ) ) > 0 ) stop ( "ERROR: A column has all missing values!")
                                        #    if (sum(col.nas)/prod(dim(x))>0.15) stop("Greater than 15% missing values in data")
    
  nas <- is.na(drop(x %*% rep(1, p)))
  xcomplete <- x[!nas, ]              # rows of x without any missing values
  xbad <- x[nas, , drop = FALSE]      # rows of x with some missing values
    
  require(pamr)
  x[nas, ] <- t ( apply ( xbad, 1, ep.nnmiss, xcomplete = xcomplete, K = k ) )
  detach("package:pamr")
  return(x)
}

ep.nnmiss <- function ( d, xcomplete, K ) {
  nnmiss ( xcomplete, d, is.na(d), K )
}
